<?php

namespace Home\Controller;


class IndexController extends HomeCommonController
{
    const TIME_SPACE = 172800;
    const SUM_MATCH_NO = 120;

    /**
     * 登录
     */
    public function index()
    {
        $code = I('code');
        $from_openid = I('shareid');

        if (!$code) {
            $index = 'http://clouddeer.cn/ddz';
            if ($from_openid) {
                $index = $index . '?shareid=' . $from_openid;
            }
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='. C('WECHAR.APP_KEY') .'&redirect_uri='. $index .'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';
            header("Location:$url");
            exit;
        }

        // 通过code换取网页授权access_token和openid
        $openidUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C('WECHAR.APP_KEY') . "&secret=" . C('WECHAR.APP_SECRET') . "&code=" . $code . "&grant_type=authorization_code";
        $openidData = json_decode(file_get_contents($openidUrl), true);

        // 通过access_token和openid拉取用户信息
        $userinfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $openidData['access_token'] . "&openid=" . $openidData['openid'] . "&lang=zh_CN";
        $userinfoData = json_decode(file_get_contents($userinfoUrl), true);

        $where = array(
            'weixinlog' => $openidData['openid']
        );
        $memberModel = M('member');
        $memberList = $memberModel->where($where)->find();
        // 非第一次登录
        if ($memberList) {
            $memberModel->where($where)->save(array('lastlogtime' => NOW_TIME));
        } else {
            $addData = array(
                'weixinlog'     => $openidData['openid'],
                'weixintoken'   => $openidData['access_token'],
                'nickname'      => $userinfoData['nickname'],
                'regtime'       => NOW_TIME,
                'lastlogtime'   => NOW_TIME
            );
            $list = $memberModel->add($addData);
            if ($list) {
                // 把微信头像拽到服务器
                $url = $this->download_remote_file($userinfoData['headimgurl'], './Uploads/Api/user/' . $this->get_avatar($list) . $this->get_avatarName($list) . '.jpg', $list);
                $memberModel->where($where)->save(array('photo_url' => $url));
            }
        }
        $wxconfig = weixinShare();
        $this->assign('match_info', $this->getCurrentMatch());
        $this->assign('openid', $openidData['openid']);
        $this->assign('wxconfig', $wxconfig);
        $this->display();
    }

    /**
     * 获取当前的比赛
     *
     * http://127.0.0.1:8093/Index/getCurrentMatch
     */
    protected function getCurrentMatch()
    {
        $where = array(
            'status' => 1
        );
        $res = M('match')->where($where)->find();
        return $res;
    }

    /**
     * 报名
     *
     * http://127.0.0.1:8093/Index/signup
     */
    public function signup()
    {
        $match = $this->getCurrentMatch();
        // 比赛有多少人报名
//        var_dump($match);
        $where = array(
            'match_id' => $match['id'],
            'status' => 1
        );
        $current = M('match_no')->where($where)->count();
//        var_dump($current); exit;
        $this->assign('current', $current);
        $this->assign('sum', self::SUM_MATCH_NO);
//        $this->display();
    }

    /**
     * 抢号
     * http://127.0.0.1:8093/Index/signUp/match_id/1
     *
     * 每场比赛120人，放号只放110个普通号 10个内定的种子选手
     * 逻辑:每次放120个号码，1-110为正式号，111 -120为替补号
     * 抢号从 2-10 12-20 22-30 从101 ~120不涉及种子选手
     */
    public function doSignUp()
    {
        $member_id = I('member_id');
        $match_id  = I('match_id');
        if (!$member_id || !$match_id) {
            $this->showMessage(array(), self::ERROR_CODE, '参数错误');
        }
        // 1 查看是否有参赛资格是否为会员
        $info = M('member')->where(array('id' => $member_id))->find();
        if ($info['is_member'] === '0') {
            $this->showMessage(array(), self::ERROR_CODE, '尚未成为会员');
        }
        if ($info['match_flg'] === '0') {
            $this->showMessage(array(), self::ERROR_CODE, '该会员不具备参赛资格');
        }

        $model = M('match_no');
        // 2 不能重复报名
        $where = array(
            'match_id' => $match_id,
            'type'     => 2,
            'status'   => 1,
            'member_id' => $member_id
        );
        $has = $model->where($where)->find();
        if ($has) {
            $this->showMessage(array(), self::ERROR_CODE, '不能重复报名');
        }
        // 3 获取当前最小的号
        $where = array(
            'match_id' => $match_id,
            'type'     => 2,
            'status'   => 0
        );

        $current = $model->field('min(no) as current')->where($where)->find();
        // 4 报名
        $data = array(
            'member_id' => $member_id,
            'status'    => 1
        );
        $where['no'] = $current['current'];
        $res = $model->where($where)->save($data);

        // 5 抢号结束后的通知
        if ($res) {
            $this->showMessage();
        } else {
            $this->showMessage(array(), self::ERROR_CODE, self::ERROR_MSG);
        }
    }

    /**
     * 提名
     *
     * http://127.0.0.1:8093/Index/nomination/member_id/1/match_id/1/name/dddd/phone/20
     * 参赛的人每人可以提名两人
     */
    public function doNomination()
    {
        $member_id = I('member_id');
        $match_id  = I('match_id');
        $name      = I('name');
        $phone     = I('phone');

        $where = array(
            'member_id' => $member_id,
            'match_id'  => $match_id
        );
        // 一个人一场比赛只能题两个
        $model = M('named');
        $count = $model->where($where)->count();
        if ($count > 2) {
            $this->showMessage(array(), self::ERROR_CODE, '每人每场比赛最多提名两个人');
        }
        // 哪一场比赛，谁提的名
        $data = array(
            'name'        => $name,
            'phone'       => $phone,
            'member_id'   => $member_id,
            'match_id'    => $match_id,
            'create_time' => NOW_TIME
        );
        $res = $model->add($data);
        if ($res) {
            $this->showMessage();
        } else {
            $this->showMessage(array(), self::ERROR_CODE, '提名失败');
        }
    }

    /**
     * 弃权
     *
     * http://127.0.0.1:8093/Index/abstain/member_id/1/match_id/1
     */
    public function abstain()
    {
        $member_id = I('member_id');
        $match_id  = I('match_id');
        if (!$member_id || !$match_id) {
            $this->showMessage(array(), self::ERROR_CODE, '参数错误');
        }
        $where = array(
            'member_id' => $member_id,
            'match_id' => $match_id
        );
        $model = M('match_no');
        // 已经弃权了，不能重复弃权
        $has = $model->where($where)->getField('status');
        if ($has === '2') {
            $this->showMessage(array(), self::ERROR_CODE, '已经取消，不能重复操作');
        }
        // 比赛已经开始，不能弃权
        $start_time = M('match')->where(array('match_id' => $match_id))->getField('start');
        $start_time = intval($start_time);

        $current_time = time();
        // 48小时以内
        if ($start_time - $current_time < self::TIME_SPACE) {
            M('member')->where(array('id' => $member_id))->save(array('match_flg' => 1));
        }
        // 弃权
        $data = array(
            'status' => 2
        );
        $res = $model->where($where)->save($data);
        if ($res) {
            $this->showMessage();
        } else {
            $this->showMessage(array(), self::ERROR_CODE, '弃权失败');
        }
    }
}